﻿using CatUtils.Utils.Currency;
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace CatUtils.Utils.Enhance.Encrypt
{
    /// <summary>
    /// Aes加密解密工具
    /// </summary>
    public class AesCryptoTool
    {
        /// <summary>
        /// 加密辅助 使用UTF8编码
        /// </summary>
        /// <param name="ToEncrypt">要加密的内容</param>
        /// <param name="sKey">密钥必须为八位英文，可配合数字</param>
        /// <returns>成功返回解码字符串，失败返回空。  The decode string is returned successfully, and null is returned in case of failure.</returns>
        public static string Encrypt(string ToEncrypt, string sKey)
        {
            return Encrypt(ToEncrypt, sKey, Encoding.UTF8);
        }

        /// <summary>
        /// 加密辅助
        /// </summary>
        /// <param name="ToEncrypt">要加密的内容</param>
        /// <param name="sKey">密钥必须为八位英文，可配合数字</param>
        ///<param name="encoding">设定加解密所用编码</param>
        /// <returns>成功返回解码字符串，失败返回空。  The decode string is returned successfully, and null is returned in case of failure.</returns>
        public static string Encrypt(string ToEncrypt, string sKey, Encoding encoding)

        {
            if (!JudgePassIsCorrect(sKey))
                return "";
            try
            {
                using (AesCryptoServiceProvider des = new AesCryptoServiceProvider())
                {
                    //把字符串放到byte数组中，原来使用的UTF8编码，我改成Unicode编码了，不行

                    byte[] inputByteArray = encoding.GetBytes(ToEncrypt);

                    //建立加密对象的密钥和偏移量，原文使用ASCIIEncoding.ASCII方法的GetBytes方法，输入密码必须输入英文文本

                    des.Key = encoding.GetBytes(sKey);

                    des.IV = encoding.GetBytes(sKey);

                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
                        {
                            //Write  the  byte  array  into  the  crypto  stream

                            //(It  will  end  up  in  the  memory  stream)

                            cs.Write(inputByteArray, 0, inputByteArray.Length);

                            cs.FlushFinalBlock();

                            //Get  the  data  back  from  the  memory  stream,  and  into  a  string

                            StringBuilder ret = new StringBuilder();

                            foreach (byte b in ms.ToArray())

                            {
                                //Format  as  hex

                                ret.AppendFormat("{0:X2}", b);
                            }

                            return ret.ToString();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                PrintLog.Log(ex);
            }
            return "";
        }

        /// <summary>
        /// 解密方法  使用UTF8编码
        /// </summary>
        /// <param name="pToDecrypt"></param>
        /// <param name="sKey">密钥必须为八位英文，可配合数字</param>
        /// <returns>成功返回解码字符串，失败返回空。  The decode string is returned successfully, and null is returned in case of failure.</returns>
        public static string Decrypt(string pToDecrypt, string sKey)
        {
            return Decrypt(pToDecrypt, sKey, Encoding.UTF8);
        }

        /// <summary>
        /// 解密方法
        /// </summary>
        /// <param name="pToDecrypt"></param>
        /// <param name="sKey">密钥必须为八位英文，可配合数字</param>
        ///<param name="encoding">设定加解密所用编码</param>
        /// <returns>成功返回解码字符串，失败返回空。  The decode string is returned successfully, and null is returned in case of failure.</returns>
        public static string Decrypt(string pToDecrypt, string sKey, Encoding encoding)

        {
            if (!JudgePassIsCorrect(sKey))
                return "";
            try
            {
                using (AesCryptoServiceProvider des = new AesCryptoServiceProvider())
                {
                    //Put  the  input  string  into  the  byte  array

                    byte[] inputByteArray = new byte[pToDecrypt.Length / 2];

                    for (int x = 0; x < pToDecrypt.Length / 2; x++)

                    {
                        int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));

                        inputByteArray[x] = (byte)i;
                    }

                    //建立加密对象的密钥和偏移量，此值重要，不能修改

                    des.Key = encoding.GetBytes(sKey);

                    des.IV = encoding.GetBytes(sKey);

                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))
                        {
                            //Flush  the  data  through  the  crypto  stream  into  the  memory  stream

                            cs.Write(inputByteArray, 0, inputByteArray.Length);

                            cs.FlushFinalBlock();

                            //Get  the  decrypted  data  back  from  the  memory  stream
                        }
                        return encoding.GetString(ms.ToArray());
                    }
                }
            }
            catch (Exception ex)
            {
                PrintLog.Log(ex);
            }

            return "";
        }

        /// <summary>
        /// 提示密码是否合规 符合返回TRUE
        /// </summary>
        /// <param name="sKey"></param>
        /// <returns></returns>
        public static bool JudgePassIsCorrect(string sKey)
        {
            if (sKey.Length != 8)
            {
                Console.WriteLine("密码不为八位纯字母数字！");
                return false;
            }
            return true;
        }
    }
}